﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using Anke.SHManage.BLL;
using System.Web.Script.Serialization;
using Anke.SHManage.Model.PatientModel;
using System.Configuration;
using System.Net;
using System.Text;

namespace Anke.SHManage.Web.Areas.PR.Controllers
{
    public class PRRescueController : Controller
    {
        //
        // GET: /PR/PRRescue/
        private JavaScriptSerializer js = new JavaScriptSerializer();

        public ActionResult Index()
        {
            return View();
        }


        #region 获取救治记录列表
        [HttpPost]
        public ActionResult GetPatientRecordRescue()
        {
            try
            {
                //string taskCode, int patientOrder, int pageSize, int pageIndex
                string taskCode = Request.Form["TaskCode"].ToString();
                int patientOrder = int.Parse(Request.Form["PatientOrder"]);

                //获取页容量
                int pageSize = int.Parse(Request.Form["rows"]);
                //获取请求的页码
                int pageIndex = int.Parse(Request.Form["page"]);

                M_PatientRecordBLL bll = new M_PatientRecordBLL();
                int total = 0;
                List<M_PatientRecordRescue> list = bll.GetPRRescueList(pageIndex, pageSize, ref total, taskCode, patientOrder);
                return Json(new { total = total, rows = list }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                LogUtility.Error("PRRescueController/GetPatientRecordRescue()", ex.ToString());
                return this.Json("");
            }
        }
        #endregion


        #region 保存病历--救治记录-病情变化 add2022-08-17 plq
        public bool EditBQBH()
        {
            M_PatientRecordRescue prRescue = null;//救治记录主表信息
            string PRRescue = Request.Form["PRRescue"].ToString();
            M_AddPatientRecordRescue add = new M_AddPatientRecordRescue();
            M_PatientRecordRescueBLL bll = new M_PatientRecordRescueBLL();
            add = JsonHelper.GetJsonInfoBy<M_AddPatientRecordRescue>(PRRescue);
            if (add != null)
            {
                prRescue = add.prRescue;//救治记录主表信息
            }
            if (prRescue != null)
            {
                bll.Modify(prRescue, "Remark", "DiseaseIFChanges", "DiseaseChangesSupplement", "LastUpdatePerson", "LastUpdateTime");
            }
            return true;
        }
        #endregion

        #region 保存病历--救治记录
        /// <summary>
        /// 保存病历--救治记录
        /// [SkipLoginAttribute]（20150828增加保存病历不检查Seesion）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [SkipLoginAttribute]
        public bool SavePRRescue()
        {
            string state = "";
            M_PatientRecordBLL bll = new M_PatientRecordBLL();
            M_PatientRecordRescue prRescue = null;//救治记录主表信息
            List<M_PatientRecordMeasure> prMeasure = null;//救治记录--救治措施
            List<M_PatientRecordDrug> prDrug = null;//救治记录--药品
            List<M_PatientRecordSanitation> prSanitation = null;//救治记录--耗材
            List<M_PatientRecordLossDrug> prLossDrug = null;//救治记录--损耗药品
            List<M_PatientRecordLossSanitation> prLossSanitation = null;//救治记录--损耗耗材

            string PRRescue = Request.Form["PRRescue"].ToString();
            M_AddPatientRecordRescue add = new M_AddPatientRecordRescue();
            add = JsonHelper.GetJsonInfoBy<M_AddPatientRecordRescue>(PRRescue);
            if (add != null)
            {
                //string TaskCode = add.TaskCode;
                //int PatientOrder = add.PatientOrder;
                state = add.state;
                prRescue = add.prRescue;//救治记录主表信息

                if (add.prMeasure.Count > 0)
                {
                    prMeasure = add.prMeasure;//救治记录--救治措施
                }
                else
                { prMeasure = null; }
                if (add.prDrug.Count > 0)
                {
                    prDrug = add.prDrug;//救治记录--药品
                }
                else
                { prDrug = null; }

                if (add.prSanitation.Count > 0)
                {
                    prSanitation = add.prSanitation;//救治记录--耗材
                }
                else
                { prSanitation = null; }

                if (add.prLossDrug.Count > 0)
                {
                    prLossDrug = add.prLossDrug;//救治记录--损耗药品
                }
                else
                { prLossDrug = null; }

                if (add.prLossSanitation.Count > 0)
                {
                    prLossSanitation = add.prLossSanitation;//救治记录--损耗耗材
                }
                else
                { prLossSanitation = null; }
            }

            bool save = false;
            if (prRescue != null)
            {
                try
                {
                    if (state == "new")
                    {
                        save = bll.InsertPRRescue(prRescue, prMeasure, prDrug, prSanitation, prLossDrug, prLossSanitation);//新增救治记录主表、子表
                    }
                    else if (state == "edit")
                    {
                        save = bll.UpdatePRRescue(prRescue, prMeasure, prDrug, prSanitation, prLossDrug, prLossSanitation);//修改救治记录主表、子表
                    }

                    //add2022-08-17 plq  新增 诊疗操作字段，更新诊疗操作--移植自闵行
                    string TaskCode = prRescue.TaskCode;
                    int PatientOrder = prRescue.PatientOrder;
                    bool updatestate = bll.UpdateMeasureInformation(TaskCode, PatientOrder); 
                }
                catch
                {
                    save = false;
                }
            }

            //add2021-11-12 plq 医保上线移植
            string useTaskCode = add.TaskCode;
            int usePatientOrder = add.PatientOrder;
            bool IsMaterialUse;
            List<M_PatientRecordDrug> mprd = new M_PatientRecordDrugBLL().GetListBy(p => p.TaskCode == useTaskCode && p.PatientOrder == usePatientOrder).ToList();
            List<M_PatientRecordSanitation> mprs = new M_PatientRecordSanitationBLL().GetListBy(p => p.TaskCode == useTaskCode && p.PatientOrder == usePatientOrder).ToList();
            List<M_PatientRecordMeasure> mprm = new M_PatientRecordMeasureBLL().GetListBy(p => p.TaskCode == useTaskCode && p.PatientOrder == usePatientOrder).ToList();
            IsMaterialUse = SavePatientRecordMaterialUse(mprd, mprs, mprm, useTaskCode, usePatientOrder);
            if (IsMaterialUse)
            {
                //int userId = UserOperateContext.Current.Session_UsrInfo.ID;
                int userId = bll.GetUserID(useTaskCode, usePatientOrder); //2021-12-24 plq 移植参考闵行，UserID赋值调整
                string errorMsg = "";
                bool retDelivery = SaveTaskDelivery(true, useTaskCode, usePatientOrder, userId, ref errorMsg);
                if (!retDelivery)
                {
                    save = false;
                }
                else
                {
                    save = true;
                }
            }
            else
            {
                save = false;
            }
            return save;
        }
        #endregion


        #region 删除病历--救治记录
        [HttpPost]
        [SkipLoginAttribute]
        public bool DeletePRRescue()
        {
            bool save = false;
            try
            {
                M_PatientRecordBLL bll = new M_PatientRecordBLL();
                string TaskCode = Request.Form["TaskCode"].ToString();
                int PatientOrder = Convert.ToInt32(Request.Form["PatientOrder"]);
                string RescueRecordCode = Request.Form["RescueRecordCode"].ToString();
                int DisposeOrder = Convert.ToInt32(Request.Form["DisposeOrder"]);
                if (TaskCode != null)
                {
                    save = bll.DeletePRRescue(TaskCode, PatientOrder, RescueRecordCode, DisposeOrder);
                }
                //add2021-11-12 plq 医保上线移植
                List<M_PatientRecordDrug> mprd = new M_PatientRecordDrugBLL().GetListBy(p => p.TaskCode == TaskCode && p.PatientOrder == PatientOrder).ToList();
                List<M_PatientRecordSanitation> mprs = new M_PatientRecordSanitationBLL().GetListBy(p => p.TaskCode == TaskCode && p.PatientOrder == PatientOrder).ToList();
                List<M_PatientRecordMeasure> mprm = new M_PatientRecordMeasureBLL().GetListBy(p => p.TaskCode == TaskCode && p.PatientOrder == PatientOrder).ToList();
                bool IsMaterialUse;
                IsMaterialUse = SavePatientRecordMaterialUse(mprd, mprs, mprm, TaskCode, PatientOrder);
                if (IsMaterialUse)
                {
                    //int userId = UserOperateContext.Current.Session_UsrInfo.ID;
                    int userId = bll.GetUserID(TaskCode, PatientOrder);  //2021-12-24 plq 移植参考闵行，UserID赋值调整
                    string errorMsg = "";
                    bool retDelivery = SaveTaskDelivery(true, TaskCode, PatientOrder, userId, ref errorMsg);
                    if (!retDelivery)
                    {
                        return false;
                    }
                    else
                    {
                        return true;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                save = false;
            }
            return save;
        }
        #endregion

        
        #region 获取救治记录
        /// <summary>
        /// 获取救治记录
        /// 20150828增加获取失败存任务编码到日志里
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [SkipLoginAttribute]
        public ActionResult GetPRRescue()
        {
            string TaskCode = "";
            try
            {
                M_PatientRecordBLL prBLL = new M_PatientRecordBLL();
                M_PatientRecordRescue prrInfo;//病历--救治记录主表
                TaskCode = Request.Form["TaskCode"].ToString();
                int PatientOrder = Convert.ToInt32(Request.Form["PatientOrder"]);
                string RescueRecordCode = Request.Form["RescueRecordCode"].ToString();
                int DisposeOrder = Convert.ToInt32(Request.Form["DisposeOrder"]);
                prBLL.GetPRRescueInfo(TaskCode, PatientOrder, RescueRecordCode, DisposeOrder, out prrInfo);

                var model = prrInfo;
                return Json(new { IsSuccess = true, Model = model });
            }
            catch (Exception ex)
            {
                LogUtility.Error("PRRescueController/GetPRRescue(" + TaskCode + ")", ex.ToString());
                return this.Json("");
            }
        }
        #endregion

        #region 2021-08-31 SR  医保上传病历调用接口 //add2021-10-18 plq 医保上线移植
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Boolean SavePatientRecordMaterialUse(List<M_PatientRecordDrug> prds, List<M_PatientRecordSanitation> prss, List<M_PatientRecordMeasure> prms, string TaskCode, int PatientOrder)
        {
            List<M_PatientRecordMaterialUse> prmu = new List<M_PatientRecordMaterialUse>();
            string strURL = "";
            string responseText = "";
            string PRecordMaterials = "";
            try
            {
                //药品
                if (prds != null)
                {
                    foreach (M_PatientRecordDrug info in prds)
                    {
                        List<I_Material> imList = new I_MaterialBLL().GetListBy(p => p.ID == info.DrugCode && p.YBCode != null && p.YBCode.Length > 0).ToList();
                        if (imList != null)
                        {
                            M_PatientRecordMaterialUse mprmu = new M_PatientRecordMaterialUse();
                            mprmu.TaskCode = info.TaskCode;
                            mprmu.PatientOrder = info.PatientOrder;
                            mprmu.PRType = 1;
                            mprmu.MaterialCode = info.DrugCode;
                            mprmu.Dosage = Convert.ToDouble(info.Dosage);
                            mprmu.SelectOrder = info.SelectOrder;
                            mprmu.Remark = info.Remark;
                            prmu.Add(mprmu);
                        }
                    }
                }
                //耗材
                if (prss != null)
                {
                    foreach (M_PatientRecordSanitation info in prss)
                    {
                        List<I_Material> imList = new I_MaterialBLL().GetListBy(p => p.ID == info.SanitationCode && p.YBCode != null && p.YBCode.Length > 0).ToList();
                        if (imList != null)
                        {
                            M_PatientRecordMaterialUse mprmu = new M_PatientRecordMaterialUse();
                            mprmu.TaskCode = info.TaskCode;
                            mprmu.PatientOrder = info.PatientOrder;
                            mprmu.PRType = 2;
                            mprmu.MaterialCode = info.SanitationCode;
                            mprmu.Dosage = Convert.ToDouble(info.NumberOfTimes);
                            mprmu.SelectOrder = info.SelectOrder;
                            mprmu.Remark = info.Remark;
                            prmu.Add(mprmu);
                        }
                    }
                }
                //救治措施
                if (prms != null)
                {
                    foreach (M_PatientRecordMeasure info in prms)
                    {
                        M_PatientRecordMaterialUse mprmu = new M_PatientRecordMaterialUse();
                        mprmu.TaskCode = info.TaskCode;
                        mprmu.PatientOrder = info.PatientOrder;
                        mprmu.PRType = 3;
                        mprmu.MaterialCode = info.RescueMeasureCode;
                        mprmu.Dosage = Convert.ToDouble(info.NumberOfTimes);
                        mprmu.SelectOrder = info.SelectOrder;
                        mprmu.Remark = info.Remark;
                        prmu.Add(mprmu);
                    }
                }
                if (prmu != null)
                {
                    if (prmu.Count > 0)
                    {
                        strURL = ConfigurationManager.AppSettings["YBWebUrlSaveUse"].ToString();
                        PRecordMaterials = JsonHelper.Obj2JsonStr(prmu); ;
                        System.Net.HttpWebRequest request;
                        request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                        //Post请求方式
                        request.Method = "POST";
                        // 内容类型
                        request.ContentType = "application/x-www-form-urlencoded";
                        // 参数经过URL编码
                        StringBuilder sb = new StringBuilder();
                        sb.Append("&PRecordMaterials=" + PRecordMaterials);
                        byte[] payload;
                        //将URL编码后的字符串转化为字节
                        payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                        //设置请求的 ContentLength 
                        request.ContentLength = payload.Length;
                        //获得请求流
                        System.IO.Stream writer = request.GetRequestStream();
                        //将请求参数写入流
                        writer.Write(payload, 0, payload.Length);
                        // 关闭请求流
                        writer.Close();
                        System.Net.HttpWebResponse response;
                        // 获得响应流
                        response = (System.Net.HttpWebResponse)request.GetResponse();
                        System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        responseText = myreader.ReadToEnd();
                        myreader.Close();
                        //解析返回的实体
                        ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                        if (rinfo.status == "0")
                        {
                            return true;
                        }
                        else
                        {
                            LogUtility.Error("PRRescueController/SavePatientRecordMaterialUse", "医保SaveUse方法失败：" + rinfo.msg);
                            return false;
                        }
                    }
                    else
                    {
                        strURL = ConfigurationManager.AppSettings["YBWebUrlDeleteUse"].ToString();
                        PRecordMaterials = JsonHelper.Obj2JsonStr(prmu); ;
                        System.Net.HttpWebRequest request;
                        request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                        //Post请求方式
                        request.Method = "POST";
                        // 内容类型
                        request.ContentType = "application/x-www-form-urlencoded";
                        // 参数经过URL编码
                        StringBuilder sb = new StringBuilder();
                        sb.Append("&TaskCode=" + TaskCode);
                        sb.Append("&PatientOrder=" + PatientOrder);
                        byte[] payload;
                        //将URL编码后的字符串转化为字节
                        payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                        //设置请求的 ContentLength 
                        request.ContentLength = payload.Length;
                        //获得请求流
                        System.IO.Stream writer = request.GetRequestStream();
                        //将请求参数写入流
                        writer.Write(payload, 0, payload.Length);
                        // 关闭请求流
                        writer.Close();
                        System.Net.HttpWebResponse response;
                        // 获得响应流
                        response = (System.Net.HttpWebResponse)request.GetResponse();
                        System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                        responseText = myreader.ReadToEnd();
                        myreader.Close();
                        //解析返回的实体
                        ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                        if (rinfo.status == "0")
                        {
                            return true;
                        }
                        else
                        {
                            LogUtility.Error("PRRescueController/SavePatientRecordMaterialUse", "医保DeleteUse方法失败：" + rinfo.msg);
                            return false;
                        }
                    }

                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("PRRescueController/SavePatientRecordMaterialUse", "程序异常：" + ex.Message);
                return false;
            }
        }
        #endregion

        #region 20210909 sr 上传收费扣库存接口 //add2021-11-12 plq 医保上线移植
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public Boolean SaveTaskDelivery(bool isCheck, string taskCode, int patientOrder, int userId, ref string errorMsg)
        {
            try
            {
                string strURL = "";
                string responseText = "";
                strURL = ConfigurationManager.AppSettings["YBWebSaveTaskDelivery"].ToString();
                System.Net.HttpWebRequest request;
                request = (System.Net.HttpWebRequest)WebRequest.Create(strURL);
                //Post请求方式
                request.Method = "POST";
                // 内容类型
                request.ContentType = "application/x-www-form-urlencoded";
                // 参数经过URL编码
                StringBuilder sb = new StringBuilder();
                sb.Append("&isCheck=" + isCheck);
                sb.Append("&taskCode=" + taskCode);
                sb.Append("&patientOrder=" + patientOrder);
                sb.Append("&userId=" + userId);
                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
                //设置请求的 ContentLength 
                request.ContentLength = payload.Length;
                //获得请求流
                System.IO.Stream writer = request.GetRequestStream();
                //将请求参数写入流
                writer.Write(payload, 0, payload.Length);
                // 关闭请求流
                writer.Close();
                System.Net.HttpWebResponse response;
                // 获得响应流
                response = (System.Net.HttpWebResponse)request.GetResponse();
                System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
                responseText = myreader.ReadToEnd();
                myreader.Close();
                //解析返回的实体
                ResultInfo rinfo = js.Deserialize<ResultInfo>(responseText);
                if (rinfo.status == "0")
                {
                    return true;
                }
                else
                {
                    errorMsg = rinfo.msg;
                    return false;
                }
            }
            catch (Exception ex)
            {
                LogUtility.Error("PatientChargeController/SaveTaskDelivery", "程序异常：" + ex.Message);
                return false;
            }
        }
        #endregion
    }
}
